<?php

class BadSectors {

	public $sectors = NULL;
	public $encoding = NULL;
	
	function __construct($html = NULL, $encoding = "") {
		$this->encoding = $encoding;
		if ($html != NULL) {
			$this->buildSectors($html);
		}
	}
	
	public function buildSectors( $html, $offset = 0 ) {
	
		preg_match_all(
				"/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/"
			, $html
			, $matches
			, PREG_SET_ORDER|PREG_OFFSET_CAPTURE
		);

		foreach ($matches as $val) {
#			print_r($val);
			switch($val[2][0]) {
				case 'iframe':
				case 'title':
				case 'style':
				case 'script':
					$this->sectors[] = array("tag" => $val[2][0], "start" => $val[1][1] + $offset, "end" => $val[4][1] + @mb_strlen($val[4][0], $this->encoding) - 1 + $offset, "status" => 0);
					break;
				
				default:
					$this->sectors[] = array("tag" => $val[2][0], "start" => $val[1][1] + $offset, "end" => $val[1][1] + @mb_strlen($val[1][0], $this->encoding) - 1 + $offset, "status" => 0);
					if ($val[3][0] != "") {
#print_r($val);
						$this->buildSectors($val[3][0], $val[3][1] + $offset);
					}
					if (isset($val[4])) $this->sectors[] = array("tag" => "/" . $val[2][0], "start" => $val[4][1] + $offset, "end" => $val[4][1] + @mb_strlen($val[4][0], $this->encoding) - 1 + $offset, "status" => 0);
					break;
			}
		}		
	}
	
	public function isSafe( $index ) {
		for($i=0;$i<count($this->sectors);$i++) {
			if ($index <= $this->sectors[$i]["end"]) {
				if ($index > $this->sectors[$i]["start"]) {
					$this->lastSector = $this->sectors[$i];
					return(false);
				} else {
					return(true);
				}
			}
		}
		return(true);
	}
	
	public function getLastBadSector() {
		return( $this->lastSector );
	}

}

?>